package xyz.xijinian.gifttalk;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import xyz.xijinian.gifttalk.category.CategoryFragment;
import xyz.xijinian.gifttalk.home.HomeFragment;
import xyz.xijinian.gifttalk.profile.ProfileFragment;
import xyz.xijinian.gifttalk.rank.RankFragment;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    // 首页下面的四个按钮
    private View mTabHome;
    private View mTabRank;
    private View mTabCategory;
    private View mTabProfile;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView () {
        // 初始化按钮控件
        mTabHome = findViewById(R.id.tab_home);
        mTabRank = findViewById(R.id.tab_rank);
        mTabCategory = findViewById(R.id.tab_category);
        mTabProfile = findViewById(R.id.tab_profile);

        // 为按钮控件设置点击事件
        mTabHome.setOnClickListener(this);
        mTabRank.setOnClickListener(this);
        mTabCategory.setOnClickListener(this);
        mTabProfile.setOnClickListener(this);
        // 通过代码来点击第一个按钮(首页按钮)
        mTabHome.performClick();
    }

    @Override
    public void onClick (View v) {
        resetTabStatus();
        // 将点击的按钮的选择状态设置为true
        v.setSelected(true);
        // 定义 Fragment 管理器,用来显示某个Fragment
        FragmentManager fm = getSupportFragmentManager();
        // 定义 Fragment 事务, 用来显示或隐藏或替换某个Fragment
        FragmentTransaction ft = fm.beginTransaction();
        switch (v.getId()) {
            case R.id.tab_home:
                ft.replace(R.id.fragment_content, new HomeFragment());
                break;
            case R.id.tab_rank:
                ft.replace(R.id.fragment_content, new RankFragment());
                break;
            case R.id.tab_category:
                ft.replace(R.id.fragment_content, new CategoryFragment());
                break;
            case R.id.tab_profile:
                ft.replace(R.id.fragment_content, new ProfileFragment());
                break;
        }
        // 提交事务, 上面的显示功能才会生效
        ft.commit();
    }

    /**
     * 用来重置所有按钮的状态, 把控件的选择状态设置为false
     */
    private void resetTabStatus(){
        mTabHome.setSelected(false);
        mTabRank.setSelected(false);
        mTabCategory.setSelected(false);
        mTabProfile.setSelected(false);
    }
}
